package com.tca.common.learning.elasticsearch;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

/**
 * @author zhoua
 * @date 2022/1/10 21:39
 * 索引操作
 */
@Slf4j
public class IndexOperator {

    /**
     * 核心客户端
     */
    private static RestHighLevelClient client = EsClientFactory.getClient();

    public static void main(String[] args) throws IOException {

        // 创建索引
//        createIndex("record_face");

        // 查询索引
//        queryIndex("record_face");

        // 删除索引
//        deleteIndex("record_face");
//        deleteIndex("user");

        // 关闭客户端
        client.close();
    }

    /**
     * 删除索引
     * @param index
     * @throws IOException
     */
    private static void deleteIndex(String index) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        log.info("删除索引: {}", response);
    }

    /**
     * 查询索引
     * @param index
     */
    private static void queryIndex(String index) throws IOException {
        GetIndexRequest recordFace = new GetIndexRequest(index);
        GetIndexResponse response = client.indices().get(recordFace, RequestOptions.DEFAULT);
        log.info("查询结果: {}", response);
        log.info("alias: {}", response.getAliases());
        log.info("mappings: {}", response.getMappings());
        log.info("settings: {}", response.getSettings());
    }

    /**
     * 创建index
     * @param index
     */
    private static void createIndex(String index) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        log.info("创建结果: {}", response);
    }
}
